
package com.bk.base;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.bk.utils.C3P0Util;

//  add()/dekete()/update()/findAll()/findById()/findByOthers()/......
public class BaseDaoImpl<T> {
	private Class targetClass;
	private String tableName;
	private String tid;
	/**
	*如何确定T的类型
	 */
	public BaseDaoImpl(){
		
		/*System.out.println(this.getClass());*/
		Class<? extends BaseDaoImpl> clz = this.getClass();
		Type type = clz.getGenericSuperclass();
		//强转子接口
		ParameterizedType ptype=(ParameterizedType)type;
		//返回表示此类型实际类型参数的 Type 对象的数组。
		Type[] typeArr = ptype.getActualTypeArguments();
		
		 targetClass=(Class)typeArr[0];
		System.out.println(targetClass);
		//表名和类名一样
		tableName=targetClass.getSimpleName();//
		tid=tableName.charAt(0)+"id";
		
	}
	
	
	
	public int add(String sql,Object...params) throws SQLException{
		QueryRunner qr=new QueryRunner(C3P0Util.getDataSource());
		return qr.update(sql, params);
	}
	public int delete(String id) throws SQLException{
		 QueryRunner qr=new QueryRunner(C3P0Util.getDataSource());
		return qr.update("delete from "+tableName+" where "+tid+"=?",id);
	}
	public int update(String sql,Object...params ) throws SQLException{
		QueryRunner qr=new QueryRunner(C3P0Util.getDataSource());
		return qr.update(sql, params);
	}
	@SuppressWarnings("unchecked")
	public T findById(String id ) throws SQLException{
		QueryRunner qr=new QueryRunner(C3P0Util.getDataSource());
		
		return qr.query("select * from "+tableName+" where "+tid+" =? ", new BeanHandler<T>(targetClass),id);
	}
	public T findById(String sql,Object...params ) throws SQLException{
		QueryRunner qr=new QueryRunner(C3P0Util.getDataSource());
		return qr.query(sql, new BeanHandler<T>(targetClass),params);
	}
	public List<T> findByOthers(String sql,Object...params) throws SQLException{
		QueryRunner qr=new QueryRunner(C3P0Util.getDataSource());
		return qr.query(sql, new BeanListHandler<T>(targetClass),params);
	}
	@SuppressWarnings("unchecked")
	public List<T> findAll() throws SQLException{
		QueryRunner qr=new QueryRunner(C3P0Util.getDataSource());
		
		return qr.query("select * from "+tableName+"", new BeanListHandler<>(targetClass));
		//return null;
	}
	

}

	